package com.deyuanyun.pic.settings.util;

import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.tool.Globals;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.settings.controller.dto.org.CompanyLogoVO;
import com.deyuanyun.pic.settings.service.org.CompanyService;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.html.*;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;
import com.itextpdf.text.pdf.BaseFont;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * pdf 工具
 * 生成单页或者多页pdf
 *
 * @author scalpel.王敏
 * @version [v1.0] 创建时间（2016/6/23）
 * @see // 引用的类
 * Method List:
 * 1.----------------
 * 2.----------------
 * History:
 */
public class HtmlToPdfUtil {

    public static void buildPdf(List<String> contexts, String destFile) throws DocumentException, IOException {
        byte[] result=buildPdf(contexts);
        FileUtils.writeByteArrayToFile(new File(destFile), result);
    }

    public static void build(String html,String name) throws DocumentException, IOException {

        name+=".pdf";
        ArrayList<String> str=new ArrayList<String>();
        str.add(Jsoup.parse(getPdfHeadHtml() + html).toString());
        HttpServletResponse response= RequestResponseContext.getResponse();
        response.setContentType("application/pdf;charset=utf-8");
//        response.setCharacterEncoding("utf-8");
        WebUtil.setDownHeader(name);
//        System.out.print(str.get(0));
        //response.setHeader("Content-Disposition", "attachment; filename=" + new String( name.getBytes("utf-8"), "ISO8859-1" ) );
        buildPdf(str,response.getOutputStream());
    }

    /**
     * html 输出流 输出pdf文件
     * @param contexts
     * @param name
     * @throws DocumentException
     * @throws IOException
     */
    public static void build(List<String> contexts,String name) throws DocumentException, IOException {

        name+=".pdf";
        HttpServletResponse response= RequestResponseContext.getResponse();
        response.setContentType("application/pdf;charset=utf-8");
//        response.setCharacterEncoding("utf-8");
        WebUtil.setDownHeader(name);
        //response.setHeader("Content-Disposition", "attachment; filename="  + new String( name.getBytes("utf-8"), "ISO8859-1" ) );
        buildPdf(contexts,response.getOutputStream());
    }
    public static void buildPdf(List<String> contexts,OutputStream out) throws DocumentException, IOException {

        byte[] result=buildPdf(contexts);
        out.write(result);
        out.flush();
//        FileUtils.writeByteArrayToFile(new File(destFile), result);
    }



    /**
     * 生成多页pdf
     * @param contexts
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static byte[] buildPdf(List<String> contexts) throws DocumentException, IOException{
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1024);
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        PdfReader reader;
        for (String ctx : contexts) {
            reader = new PdfReader(buildPdf(ctx));
            copy.addDocument(reader);
            reader.close();
        }
        document.close();
        byte[] result=baos.toByteArray();
        baos.flush();
        baos.close();
        return result;
    }

    /**
     * 生成单页pdf
     * @param ctx
     * @return
     * @throws DocumentException
     * @throws IOException
     */
    public static byte[] buildPdf(String ctx) throws DocumentException, IOException{
        ByteArrayOutputStream baos=new ByteArrayOutputStream(1024);
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, baos);
        writer.setInitialLeading(12);//文字间距
        document.open();
        HtmlToPdfUtil.MyFontsProvider fontProvider = new HtmlToPdfUtil.MyFontsProvider();
        fontProvider.addFontSubstitute("lowagie", "garamond");

        fontProvider.setUseUnicode(true);
        CssAppliers cssAppliers = new CssAppliersImpl(fontProvider);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
        DefaultTagProcessorFactory tpf=(DefaultTagProcessorFactory)Tags.getHtmlTagProcessorFactory();
        tpf.addProcessor(HTML.Tag.IMG, Image.class.getName());//默认是com.itextpdf.tool.xml.html.Image|自个定义一个image的处理类
        htmlContext.setTagFactory(tpf);
        CSSResolver cssResolver = XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
        Pipeline<?> pipeline = new CssResolverPipeline(cssResolver,new HtmlPipeline(htmlContext, new PdfWriterPipeline(document,writer)));
        XMLWorker worker = new XMLWorker(pipeline, true);
        XMLParser p = new XMLParser(worker);
        ByteArrayInputStream bais=new ByteArrayInputStream(ctx.getBytes());
        p.parse(new InputStreamReader(bais));
        p.flush();

        document.close();
        byte[] result=baos.toByteArray();
        baos.flush();
        baos.close();
        return result;
    }


    public static class MyFontsProvider extends XMLWorkerFontProvider{
        public MyFontsProvider(){
            super(null,null);
        }
        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
            String fntname = fontname;
            if(fntname==null){
                fntname="宋体";
            }
            try {
                String path = this.getClass().getResource("/").getPath();
                if(path.indexOf(":") == 2)
                {
                    path = path.substring(1);
                }
                final BaseFont bf = BaseFont.createFont(path + "pdfFile/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                Font font = new Font(bf, size, style);
//                font.setColor(color);
                return font;
            }catch (IOException e) {
                e.printStackTrace();
            } catch (DocumentException e) {
                e.printStackTrace();
            }

            return super.getFont(fntname, encoding, size, style);
        }
    }



    /**
     *  将图片文件转化为字节数组字符串，并对其进行Base64编码处理
     * @param imgFilePath
     * @return
     */
    public static String getImageStr(String imgFilePath) {
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data).replaceAll("\r","").replaceAll("\n","");// 返回Base64编码过的字节数组字符串
    }

    private static String getPdfHeadHtml()
    {
        String sysDate = com.deyuanyun.pic.common.util.StringUtils.convertDateToString(new Date(),"yyyy-MM-dd");
        CompanyService companyService = SpringAppliction.getBean(CompanyService.class);
        CompanyLogoVO companyLogoVO = companyService.getUserCompanyLogo();
        if (companyLogoVO == null || StringUtils.isEmpty(companyLogoVO.getLogoPath())) {
            companyLogoVO = new CompanyLogoVO();

            if(Globals.getProperties("logo") != null)
            {
                companyLogoVO.setLogoPath(getPath() + Globals.getProperties("logo"));
                companyLogoVO.setName(Globals.getProperties("companyName"));
            }else{
                companyLogoVO.setLogoPath(getPath()+"/template/logo.png");
                companyLogoVO.setName("四川德源云管道信息技术有限公司");
            }

        }

        String type = companyLogoVO.getLogoPath().substring(companyLogoVO.getLogoPath().lastIndexOf(".")+1);
        String fileName = RequestResponseContext.getRequest().getParameter("fileName");
        StringBuilder head = new StringBuilder();
        head.append("<style  type=\"text/css\">");


        head.append("html,body{margin: 0; padding: 0; font-size: 14px;font-family: Arial Unicode MS;}");
        head.append(".l{float: left;}");
        head.append(".r{float: right;}");
        head.append(".zy-pdf-head{height: 100px; width: 100%;padding-top:-30px;}");
        head.append(".head-title{line-height: 30px;padding-top:-10px;}");
        head.append(".zy-pdf-head-logo{ }");
        head.append(".zy-pdf-logo-span{width:60px;  }");
        head.append(".zy-pdf-text-span{width:300px;line-height: 40px;  }");
        head.append(".line{border-bottom: 1px solid #bfbfbf;  }");
        head.append(".zy-pdf-head-title{line-height: 30px; text-align: center; font-size: 24px; margin: 0 5px;}");
        head.append("</style>");
        head.append("<div class=\"zy-pdf-head\">");
        head.append("        <div class=\"zy-pdf-head-logo\">");
        head.append("<div class=\"zy-pdf-logo l\">");
        head.append("   <div class=\"zy-pdf-logo-span l\">").append("<img width='50'  src='data:image/"+type+";base64,").append(getImageStr(companyLogoVO.getLogoPath())).append("' />").append("</div>");
        head.append("   <div class=\"zy-pdf-text-span l\">").append(companyLogoVO.getName()).append("</div>");
        head.append("   <div class=\"clear\"></div>");
        head.append("</div>");
        head.append("            <div class=\"zy-pdf-date r head-title\">");
        head.append("                <span id=\"JQ_pdf_date\" class=\"zy-pdf-text-span\">日期:" +sysDate+ "</span>");
        head.append("            </div>");
        head.append("            <div class=\"clear\"></div>");
        head.append("        </div>");
        head.append("        <div class=\"zy-pdf-head-title\">");
        head.append("            <div id=\"JQ_pdf_title\">"+fileName+"</div>");
        head.append("        </div>");

        head.append("    </div>");

        String lineName = RequestResponseContext.getRequest().getParameter("lineName");
        String beginName = RequestResponseContext.getRequest().getParameter("beginName");
        String endName = RequestResponseContext.getRequest().getParameter("endName");
        if(!StringUtils.isEmpty(lineName))
        {
            head.append("<div style=\"width:330px;float:left;\">").append("管道名称:").append(lineName).append("</div>");
            head.append("<div style=\"width:350px;float:left;\">");
            if(!StringUtils.isEmpty(beginName)) {
                head.append("起点位置:").append(beginName);


            }
            if(!StringUtils.isEmpty(endName)) {
                head.append("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;终点位置:").append(endName);
            }
          head.append("</div>");
        }


        head.append("<hr size=1 />");

//        System.out.println(head);
        return head.toString();
    }

    public static void main(String[] args) throws IOException, DocumentException {
//        System.out.println(getImageStr("z:\\bg_1.png"));
        String DEST = "z:/test2015-11.pdf";
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        ArrayList<String> str=new ArrayList<String>();
        org.jsoup.nodes.Document doc= Jsoup.parse(getPdfHeadHtml());//"<div>中文hello</div><br><img src=\"\">");

        System.out.println(doc.toString());
        str.add(doc.toString());
        HtmlToPdfUtil.buildPdf(str, DEST);
    }


    public static String getPath()
    {
        String path = HtmlToPdfUtil.class.getResource("/").getPath();
        if(path.indexOf(":") == 2)
        {
            path = path.substring(1);
        }
        return path;
    }
}


